import plugin from '../../../lib/plugins/plugin.js'
import command from '../command/command.js'
import fetch from 'node-fetch'
import { segment } from 'oicq'
import { createRequire } from "module";

const require = createRequire(import.meta.url);


export class SharpnessEnhancement extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '清晰度增强',
            /** 功能描述 */
            dsc: '图片（动漫风格图最佳）清晰度增强',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 1002,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '^#*清晰度(增强|提升)$',
                    /** 执行方法 */
                    fnc: 'SharpnessEnhancement'
                }
            ]
        })
    }

    /**
     * 
     * @param e oicq传递的事件参数e
     */
    async SharpnessEnhancement(e) {

        if (this.e.source) {
            let reply;
            if (this.e.isGroup) {
                reply = (await this.e.group.getChatHistory(this.e.source.seq, 1)).pop()?.message;
            } else {
                reply = (await this.e.friend.getChatHistory(this.e.source.time, 1)).pop()?.message;
            }

            if (reply) {
                for (let val of reply) {
                    if (val.type == "image") {
                        this.e.img = [val.url];
                        break;
                    }
                }
            }
        }

        if (!this.e.img) {
            this.setContext('dealSEImg');
            await this.reply(" 请发送需要提升清晰度的图片", false, { at: true });
        } else {
            this.dealSEImg();
        }

    }
    async dealSEImg() {

        if (!this.e.img) {
            return true;
        }

        const deepai = require('deepai');
        deepai.setApiKey(await command.getConfig("deepai", "key"));
        var result = await deepai.callStandardApi("waifu2x", {
            image: this.e.img[0]
        });

        let responseImage = await fetch(result.output_url ? result.output_url : this.e.img[0]);
        if (!responseImage.ok) {
            await this.e.reply([segment.at(this.e.user_id), "获取图片失败"]);
            return true;
        }

        if (!(await command.getConfig("tencent", "SecretId"))) {
            this.e.reply(segment.image(result.output_url ? result.output_url : this.e.img[0]));
            this.finish('dealSEImg');
            return true;
        }
        let buffer = await responseImage.arrayBuffer();
        let imgBase64 = Buffer.from(buffer).toString('base64');
        const tencentcloud = require("tencentcloud-sdk-nodejs");
        const TiiaClient = tencentcloud.tiia.v20190529.Client;
        const clientConfig = {
            credential: {
                secretId: await command.getConfig("tencent", "SecretId"),
                secretKey: await command.getConfig("tencent", "SecretKey"),
            },
            region: "ap-shanghai",
            profile: {
                httpProfile: {
                    endpoint: "tiia.tencentcloudapi.com",
                },
            },
        };

        const client = new TiiaClient(clientConfig);
        const params = {
            "ImageBase64": imgBase64
        };
        client.EnhanceImage(params).then(
            async (data) => {
                await this.e.reply(segment.image(`base64://${data.EnhancedImage}`));
            },
            async (err) => {
                console.error("error", err);
                await this.e.reply(`error！\n${err}`);
            }
        );

        this.finish('dealSEImg');
    }
}